from flask import Flask, render_template, request, jsonify, redirect, url_for, session
from flask_sqlalchemy import SQLAlchemy
import bcrypt
import time
import random
import os
from datetime import datetime

app = Flask(__name__)
app.config['SECRET_KEY'] = '58ba72d0c608a255ba5435803441852b'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost:3306/deeplonk'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True

db = SQLAlchemy(app)


# 数据模型
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(255), nullable=False)


class ChatHistory(db.Model):
    __tablename__ = 'chat_history'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    role = db.Column(db.String(20), nullable=False)
    message = db.Column(db.Text, nullable=False)
    timestamp = db.Column(db.DateTime, default=db.func.current_timestamp())


# DeepSeek API 集成
def get_deepseek_response(user_message):
    try:
        import requests
        import json

        api_key = "your_deepseek_api_key"
        api_url = "https://api.deepseek.com/v1/chat/completions"

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}"
        }

        payload = {
            "model": "deepseek-chat",
            "messages": [
                {"role": "system",
                 "content": "你是虚拟奶龙，一个可爱、有趣的AI助手，以奶龙的风格与人对话。请使用温暖、友好的语气，多用可爱的表情符号。"},
                {"role": "user", "content": user_message}
            ],
            "temperature": 0.7,
            "max_tokens": 1000
        }

        # 实际环境中取消注释下面的代码
        # response = requests.post(api_url, headers=headers, data=json.dumps(payload))
        # if response.status_code == 200:
        #     return response.json()["choices"][0]["message"]["content"]
        # else:
        #     print(f"API请求失败: {response.status_code}, {response.text}")
        #     return "抱歉，我暂时无法回答这个问题。"

        # 开发环境中使用模拟回复
        return generate_mock_response(user_message)

    except Exception as e:
        print(f"调用DeepSeek API时出错: {e}")
        return "抱歉，发生了错误，请稍后再试。"


# 模拟DeepSeek回复
def generate_mock_response(user_message):
    message_rules = {
        "你好": ["你好呀~ o(^▽^)o 我是虚拟奶龙，有什么我可以帮助你的吗？", "哈喽~(≧∇≦)ﾉ 今天过得怎么样？"],
        "名字": ["我是可爱的虚拟奶龙呀！(๑•̀ㅂ•́)و✧", "我叫奶龙，很高兴认识你！(≧∇≦)ﾉ"],
        "吃": ["我不吃饭，只需要电力就能运行哦！(๑>ᴗ<๑)", "我听说人类的食物很美味，但我尝不到呢~( ´･ω･)ﾉ(._.`)"],
        "天气": ["我没办法获取实时天气呢，你可以看看窗外或者查查天气预报~(๑•́ω•̀๑)",
                 "天气变化多端，记得随时关注哦！(๑•̀ㅂ•́)و✧"],
        "帮助": ["我可以陪你聊天、解答问题，还能给你讲笑话呢！(≧∇≦)ﾉ", "有什么想聊的，尽管告诉我！(๑>ᴗ<๑)"],
        "再见": ["再见啦，祝你有个美好的一天！(๑•̀ㅂ•́)و✧", "拜拜~ 记得想我哦！(≧∇≦)ﾉ"],
        "默认": ["我不太理解你的意思呢，可以换一种表达方式吗？(๑•́ω•̀๑)", "请再说清楚一点，我会尽力回答你的！(≧∇≦)ﾉ"]
    }

    for keyword, responses in message_rules.items():
        if keyword.lower() in user_message.lower():
            return random.choice(responses)

    return random.choice(message_rules["默认"])


# 登录页面
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        user = User.query.filter_by(username=username).first()

        if user and bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')):
            session['user_id'] = user.id
            session['username'] = user.username
            return redirect(url_for('index'))
        else:
            return render_template('login.html', error='用户名或密码错误')

    return render_template('login.html')


# 注册页面
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        confirm_password = request.form.get('confirm_password')

        if password != confirm_password:
            return render_template('register.html', error='两次输入的密码不一致')

        try:
            if User.query.filter_by(username=username).first():
                return render_template('register.html', error='用户名已存在')

            password_hash = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')

            new_user = User(
                username=username,
                password=password_hash
            )

            db.session.add(new_user)
            db.session.commit()

            return redirect(url_for('login'))

        except Exception as e:
            db.session.rollback()
            import traceback
            traceback.print_exc()  # 打印详细堆栈信息
            return render_template('register.html', error=f'注册失败: {str(e)}')

    return render_template('register.html')


# 登出
@app.route('/logout')
def logout():
    session.pop('user_id', None)
    session.pop('username', None)
    return redirect(url_for('login'))


# 清空聊天历史
@app.route('/clear_history', methods=['POST'])
def clear_history():
    if 'user_id' not in session:
        return jsonify({"error": "请先登录"}), 401

    try:
        ChatHistory.query.filter_by(user_id=session['user_id']).delete()
        db.session.commit()
        return jsonify({"success": True})
    except Exception as e:
        print(f"清空历史记录时出错: {e}")
        return jsonify({"error": "清空历史记录失败"}), 500


# 聊天主页
@app.route('/')
def index():
    if 'user_id' not in session:
        return redirect(url_for('login'))

    history = ChatHistory.query.filter_by(user_id=session['user_id']).order_by(ChatHistory.timestamp.asc()).all()

    return render_template('index.html', username=session.get('username'), history=history)


# 异步消息接口
@app.route('/send_message', methods=['POST'])
def send_message():
    if 'user_id' not in session:
        return jsonify({"error": "请先登录"}), 401

    user_message = request.json.get('message', '').strip()

    if not user_message:
        return jsonify({"error": "消息不能为空"}), 400

    user_msg = ChatHistory(
        user_id=session['user_id'],
        role='user',
        message=user_message
    )
    db.session.add(user_msg)

    bot_response = get_deepseek_response(user_message)

    bot_msg = ChatHistory(
        user_id=session['user_id'],
        role='bot',
        message=bot_response
    )
    db.session.add(bot_msg)

    db.session.commit()

    return jsonify({
        "message": bot_response,
        "timestamp": time.time(),
        "role": "bot"
    })


# 测试数据库连接
@app.route('/test_db')
def test_db():
    try:
        result = db.engine.execute("SELECT 1")
        return jsonify({"status": "success", "message": "数据库连接正常"})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500


if __name__ == '__main__':
    with app.app_context():
        try:
            if not db.engine.has_table('users'):
                db.create_all()
                print("✅ 已成功创建 'users' 表")
            else:
                print("✅ 'users' 表已存在")
        except Exception as e:
            print(f"❌ 创建表时出错: {e}")

    app.run(debug=True)